package com.lagou.utils;

import java.sql.*;

public class JDBCUtils {

    // 1.将连接信息定义为字符串常量
    public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/Test01?characterEncoding=UTF-8";
    public static final String USER = "root";
    public static final String PASSWORD = "951220";

    // 2.编写静态代码块，随着类的加载而初始化完毕，注册驱动
    static {
        try {
            Class.forName(DRIVERNAME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    // 3.获取连接的静态方法
    public static Connection getConnection() {
        try {
            // 获取连接并返回
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
            return  connection;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 4.关闭增删改资源的方法
    public static void methodClose(Connection connection, Statement statement) {
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    // 5.关闭查询资源的方法
    public static void methodClose(Connection connection, Statement statement, ResultSet resultSet) {
        if (null != resultSet) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != statement) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
